package com.qidian.tcba.auth.api.controller;

import com.qidian.tcba.auth.entity.UserEntity;
import com.qidian.tcba.auth.param.LoginParam;
import com.qidian.tcba.auth.param.UserParam;
import com.qidian.tcba.auth.service.AuthUserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:fyl
 * @date 2021/7/22 20:13
 * @Modified By:
 * @Modified Date:
 * @Description:
 */
@RestController
@RequestMapping("/authUser")
public class LoginController {
    private final AuthenticationManager authenticationManager;

    private final PasswordEncoder passwordEncoder;

    private final AuthUserService userService;

    public LoginController(AuthenticationManager authenticationManager, PasswordEncoder passwordEncoder, AuthUserService userService) {
        this.authenticationManager = authenticationManager;
        this.passwordEncoder = passwordEncoder;
        this.userService = userService;
    }

    @PostMapping("/login")
    public String login(@RequestBody LoginParam param) {
        // 生成一个包含账号密码的认证信息
        Authentication token = new UsernamePasswordAuthenticationToken(param.getUsername(), param.getPassword());
        // AuthenticationManager校验这个认证信息，返回一个已认证的Authentication
        Authentication authentication = authenticationManager.authenticate(token);
        // 将返回的Authentication存到上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return "登录成功";
    }



    @PostMapping("/register")
    public String register(@RequestBody UserParam param) {
        UserEntity user = new UserEntity(param.getUsername(),  param.getPassword(), null);
        // 调用加密器将前端传递过来的密码进行加密
        user.setUsername(param.getUsername());
        user.setPassword(passwordEncoder.encode(param.getPassword()));
        // 将用户实体对象添加到数据库
        userService.save(user);
        return "注册成功";
    }
}
